# models/user.py
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.orm import declarative_base
from datetime import datetime
from .order import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    email = Column(String(100), unique=True, index=True)
    password_hash = Column(String(128), nullable=False)
    role = Column(String(20), default="user", nullable=False)  # root, manager, user
    country = Column(String(100))  # 用户可访问的国家，仅对user角色有效
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    last_login = Column(DateTime)

    def __repr__(self):
        return f"<User {self.username}>"

    def has_permission(self, required_role, target_country=None):
        """
        检查用户是否有权限执行操作
        :param required_role: 所需的最低角色权限
        :param target_country: 目标国家（仅对user角色检查）
        :return: bool
        """
        # 角色权限等级
        role_hierarchy = {
            "user": 1,
            "manager": 2,
            "root": 3
        }
        
        user_role_level = role_hierarchy.get(self.role, 0)
        required_role_level = role_hierarchy.get(required_role, 0)
        
        # 如果用户角色等级低于所需等级，拒绝访问
        if user_role_level < required_role_level:
            return False
            
        # 对于user角色，检查国家权限
        if self.role == "user" and target_country and self.country:
            return self.country == target_country
            
        return True

    def can_view_order(self, order_country):
        """检查用户是否可以查看指定国家的订单"""
        return self.has_permission("user", order_country)

    def can_view_customer(self, customer_country):
        """检查用户是否可以查看指定国家的客户"""
        return self.has_permission("user", customer_country)

    def can_add_order(self):
        """检查用户是否可以添加订单"""
        return self.has_permission("manager")

    def can_add_customer(self):
        """检查用户是否可以添加客户"""
        return self.has_permission("manager")